<template>
  <div class="app-container">
    <el-button @click="clickFn">清空</el-button>
    <el-button @click="exportToExcel">导出表格</el-button>
    <el-button @click="generateUserStats">生成用户统计</el-button>
    <!-- <el-button @click="playFn">计算月复购率</el-button>
    <el-button @click="weekFn">周复购率</el-button>
    <el-button @click="dayFn">日复购率</el-button> -->

    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>

    <hr>

    <table class="bordered-table" v-if="filteredGroups.length > 0">
      <thead>
        <tr>
          <th>标签组</th>
          <th>筛选出的无充值记录账户</th>
          <th>首次充值时间</th>
          <th>最后充值时间</th>
          <th>充值时间跨度</th>
          <th>用户总充值金额</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="(group, index) in filteredGroups">
          <tr :key="'group-' + index">
            <td :rowspan="group.accounts.length + 1">{{ group.label }}</td>
          </tr>
          <tr v-for="(account, i) in group.accounts" :key="'account-' + i +  Math.random()">
            <td>{{ account.account }}</td>
            <td>{{ account.firstRechargeTime }}</td>
            <td>{{ account.lastRechargeTime }}</td>
            <td>{{ account.rechargeTimeSpan }}</td>
            <td>{{ account.totalRechargeAmount }}</td>
          </tr>
        </template>
      </tbody>
    </table>

  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { timestampToDateTimeString, timeChangeStr, parseTime, findovertwo, getZeroTimeStamps } from '@/utils'
import * as XLSX from 'xlsx'

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      labelGroups: [],
      filteredGroups: [], 
      arrData: [],
      tableData: [],
      tableHeader: [],
      countData: [],
      countHeader: [],
      dateArr: [] // 充值 时间记录
    }
  },
  methods: {
    generateUserStats() {
      console.log(this.groupDataByLabel())
      console.log(this.filterGroupsByRecharge())
      this.labelGroups = this.groupDataByLabel()
      this.filteredGroups = this.filterGroupsByRecharge()
    },
    calculateTimeSpan(startTime, endTime) {
      const start = new Date(startTime);
      const end = new Date(endTime);
      const timeDiff = Math.abs(end - start);
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      return days > 0 ? `${days} 天` : '少于一天';
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 导入表格
    handleSuccess({ results, header }) {
      console.log(51, results, header);
      const dateArr = []
      results.map(item => {
        console.log('item', item);
        // dateArr.push(timestampToDateTimeString(item['充值时间']))
        item['充值时间'] = timeChangeStr(item['充值时间'])
        item['注册时间'] = timeChangeStr(item['注册时间'])
      })
      // parseTime('{y}-{m}-{d} {h}:{i}')
      this.dateArr = dateArr
      this.tableData = results
      this.tableHeader = header
      console.log(71, results);
      this.$store.commit('user/SET_TABLE_DATA', results) // 存到vuex
      this.$store.dispatch('user/setHeader', header)
    },
    // 清空数据
    clickFn() {
      this.tableData = []
      this.tableHeader = []
      this.$store.commit('user/DEL_TABLE')
    },
    ComputedFn() {
      let label = []
      const data = []
      this.tableData.map(item => {
        // console.log(item['标签'])
        label.push(item['标签'])
      })
      label = new Set(label)
      const lableArr = Array.from(label)
      lableArr.map((x, index) => {
        const aa = this.tableData.filter(item => {
          if (item['标签'] === x) {
            return item
          }
        })
        data.concat(aa)
      })
    },
    // 导出
    exportToExcel() {
      const data = [];
      console.log('this.filteredGroups', this.filteredGroups);
      if (!Array.isArray(this.filteredGroups)) {
          console.error('filteredGroups is not defined or not an array');
          return;
        }
        for (const group of this.filteredGroups) {
        debugger
        for (const record of group.accounts) {
          data.push({
            '标签组': group.label,
            '筛选出的无充值记录账户': record.account,
            '最后充值时间': record.lastRechargeTime,
            '首次充值时间': record.firstRechargeTime,
            '充值时间跨度': record.rechargeTimeSpan,
            '用户总充值金额': record.totalRechargeAmount
          });
        }
      }

      console.log('data', data);

      const worksheet = XLSX.utils.json_to_sheet(data);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '用户统计');
      const excelBuffer = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });

      this.saveExcelFile(excelBuffer, '用户统计.xlsx');
    },
    saveExcelFile(buffer, fileName) {
      const data = new Blob([buffer], { type: 'application/octet-stream' });

      if (typeof window.navigator.msSaveBlob !== 'undefined') {
        // For IE browser
        window.navigator.msSaveBlob(data, fileName);
      } else {
        const url = window.URL.createObjectURL(data);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      }
    },
    //计算逻辑
    filterGroups(data) {
        const filteredData = [];
        const accounts = {};

        data.forEach(entry => {
          const account = entry.充值帐户;
          const rechargeTime = new Date(entry.充值时间);

          if (!accounts[account]) {
            accounts[account] = {
              account: account,
              lastRechargeTime: rechargeTime,
              firstRechargeTime: rechargeTime,
              totalRechargeAmount: entry.充值金额
            };
          } else {
            if (rechargeTime > accounts[account].lastRechargeTime) {
              accounts[account].lastRechargeTime = rechargeTime;
            }
            if (rechargeTime < accounts[account].firstRechargeTime) {
              accounts[account].firstRechargeTime = rechargeTime;
            }
            accounts[account].totalRechargeAmount += entry.充值金额;
          }
        });

        for (const account in accounts) {
          const firstRechargeTime = accounts[account].firstRechargeTime;
          const lastRechargeTime = accounts[account].lastRechargeTime;
          console.log(190, lastRechargeTime , firstRechargeTime);
          const rechargeTimeSpan = (lastRechargeTime.getDate() - firstRechargeTime.getDate()) +1

          filteredData.push({
            label: accounts[account].标签,
            account: account,
            lastRechargeTime: this.formatDate(accounts[account].lastRechargeTime),
            firstRechargeTime: this.formatDate(accounts[account].firstRechargeTime),
            rechargeTimeSpan: rechargeTimeSpan,
            totalRechargeAmount: accounts[account].totalRechargeAmount
          });
        }

        return filteredData;
      },
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    groupDataByLabel() {
      const groups = {};
      this.tableData.forEach(entry => {
        const label = entry.标签;
        if (groups[label]) {
          groups[label].push(entry);
        } else {
          groups[label] = [entry];
        }
      });
      return Object.keys(groups).map(label => ({ label, accounts: groups[label] }));
    },
    filterGroupsByRecharge() {
      const today = new Date().getTime()
      const halfMonthAgo = new Date();
      halfMonthAgo.setDate(new Date().getDate() - 15);
      console.log(this.labelGroups,68);

      return this.labelGroups.map(group => {
        // debugger
        const filteredAccounts = group.accounts.filter(account => {
          const rechargeTime = new Date(account.充值时间).getTime()
          // console.log('rechargeTime',rechargeTime);
          // console.log('halfMonthAgo.getTime()',halfMonthAgo.getTime());
          return rechargeTime <= halfMonthAgo.getTime()
        });

        console.log('filteredAccounts', filteredAccounts);
        const filterData = this.filterGroups(filteredAccounts)
        console.log(138,filterData);

        const lastRechargeTime = filteredAccounts.length > 0 ? filteredAccounts[0].充值时间 : '-';
        const firstRechargeTime = filteredAccounts.length > 0 ? filteredAccounts[filteredAccounts.length - 1].充值时间 : '-';
        const rechargeTimeSpan = filteredAccounts.length > 0 ? this.calculateTimeSpan(firstRechargeTime, lastRechargeTime) : '-';
        const totalRechargeAmount = filteredAccounts.reduce((total, account) => total + account.充值金额, 0);

        return {
          label: group.label,
          accounts: filterData.map(x => ({
            account: x.account,
            lastRechargeTime: x.lastRechargeTime,
            firstRechargeTime: x.firstRechargeTime,
            rechargeTimeSpan: x.rechargeTimeSpan,
            totalRechargeAmount: x.totalRechargeAmount
          })),
          lastRechargeTime,
          firstRechargeTime,
          rechargeTimeSpan,
          totalRechargeAmount
        };
      });
    },
    calculateTimeSpan(startTime, endTime) {
      const start = new Date(startTime);
      const end = new Date(endTime);
      const timeDiff = Math.abs(end - start);
      const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
      return `${days} 天`;
    }
  
  }
}
</script>

<style scoped>
.bordered-table {
  border-collapse: collapse;
  width: 100%;
}

.bordered-table th,
.bordered-table td {
  border: 1px solid #ccc;
  padding: 8px;
}

.bordered-table th {
  background-color: #f2f2f2;
}

.bordered-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.bordered-table tr:hover {
  background-color: #ebebeb;
}
</style>